package prototype;

import iterator.Floor;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ProtoTypePatternDemo
 * @Description 原型模式
 * @Author leejiliang
 * @DateTime 2021/2/24 15:14
 * @Version 1.0
 */
public class ProtoTypePatternDemo {

	public static void main(String[] args) throws CloneNotSupportedException {
		final Building building = new Building();
		building.setName("大裤衩");
		building.getFloors().add(new Floor("一楼"));

		//拷贝一个 building对象?
		final Building clone= (Building) building.clone();
		System.out.println(clone);

		building.setName("大裤衩 2");
		building.getFloors().add(new Floor("二楼"));

		System.out.println(clone);

		System.out.println(building);
	}

	public static class Building{

		@Override
		public String toString() {
			return "Building{" +
					"name='" + name + '\'' +
					", floors=" + floors +
					'}';
		}

		private String name;
		private List<Floor> floors = new ArrayList<>();

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public List<Floor> getFloors() {
			return floors;
		}

		public void setFloors(List<Floor> floors) {
			this.floors = floors;
		}

		@Override
		protected Object clone() throws CloneNotSupportedException {
			final Building building = new Building();
			building.setName(getName());

			final List<Floor> floors = getFloors();
			floors.forEach(i-> {
				try {
					building.getFloors().add((Floor) i.clone());
				} catch (CloneNotSupportedException e) {
					e.printStackTrace();
				}
			});
			return building;
		}
	}

	public static class Floor{
		private String name;

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public Floor(String name) {
			this.name = name;
		}

		@Override
		protected Object clone() throws CloneNotSupportedException {
			return new Floor(getName());
		}

		@Override
		public String toString() {
			return "Floor{" +
					"name='" + name + '\'' +
					'}';
		}
	}
}
